/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */
package com.hiddenequity.acts;

import java.util.HashMap;
import java.util.Map;

import com.hiddenequity.campaign_service.CampaignFormAddSetLogic;
import com.hiddenequity.campaign_service.CampaignResponseParser;
import com.hiddenequity.campaign_service.CampaignService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Converter;
import com.hiddenequity.utils.DataValidator;
import com.hiddenequity.utils.Communication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;

public class Act_CampaignGeneral extends Act_Super{
	
	private String campaignId;
	private String biddingStrategyTransition;
	
	
	private EditText editCampaignName;
	private EditText editCampaignBudget;
	private RadioButton rb_delivery_method_standart;
	private RadioButton rb_delivery_method_accelerated;
	private RadioButton rb_adRotation_optimized;
	private RadioButton rb_adRotation_rotate;
	private CheckBox cb_GoogleSearch;
	private CheckBox cb_SearchPartners;
	private CheckBox cb_DisplayNetwork;
	private RadioButton rb_Broadest;
	private RadioButton rb_AllNetworks;   
	private  CheckBox cb_BidingLimit;
	private RadioButton rb_BidingAutomatic;
	private RadioButton rb_BidingManual;
	private EditText editBidingLimit;
	

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_campaign_general)).inflate();
        
        Intent intent = getIntent();
        campaignId = intent.getStringExtra("campaignId");
        
        sub_title.setVisibility(View.GONE);
        filter.setVisibility(View.GONE);
        
        // get form fields
        editCampaignName = (EditText) findViewById(R.id.editCampaignName);
        editCampaignBudget = (EditText) findViewById(R.id.editBudgetAmount);
    	rb_delivery_method_standart = (RadioButton) findViewById(R.id.rb_delivery_method_standart);
    	rb_delivery_method_accelerated = (RadioButton) findViewById(R.id.rb_delivery_method_accelerated);
    	cb_GoogleSearch = (CheckBox) findViewById(R.id.cb_GoogleSearch);
    	cb_SearchPartners = (CheckBox) findViewById(R.id.cb_SearchPartners);
        cb_DisplayNetwork = (CheckBox) findViewById(R.id.cb_DisplayNetwork);
        rb_Broadest = (RadioButton) findViewById(R.id.rb_Broadest);
        rb_AllNetworks = (RadioButton) findViewById(R.id.rb_AllNetworks);   
        cb_BidingLimit = (CheckBox) findViewById(R.id.cb_BidingLimit);
        rb_BidingAutomatic = (RadioButton) findViewById(R.id.rb_BidingAutomatic);
        rb_BidingManual = (RadioButton) findViewById(R.id.rb_BidingManual);
        editBidingLimit = (EditText) findViewById(R.id.editBidingLimit);
    	rb_adRotation_optimized = (RadioButton) findViewById(R.id.rb_adRotation_optimized);
    	rb_adRotation_rotate = (RadioButton) findViewById(R.id.rb_adRotation_rotate);
        
        if(campaignId != null){
        	title.setText(R.string.title_campaign_set);
        	runOperationAsync(OPERATION_GET_DATA, getString(R.string.progress_loading), false);
        } else {
        	title.setText(R.string.title_campaign_add);
        }
    }//onCreate
    

    
	/*
	 * Asinc data request
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_CampaignGeneral.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_CampaignGeneral.this.getCampaignData();
							break;
						case OPERATION_SET_DATA:
							Act_CampaignGeneral.this.campaignAddSetOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_CampaignGeneral.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								setUpForm();
								break;
							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
								break;
							}

						} else {
							Intent intent = new Intent(Act_CampaignGeneral.this
									.getApplicationContext(), Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync
    

	
    /*
     * Override back press button(non-Javadoc)
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
    	finishActivityWithResult(RESPONSE_NO_REFRESH_REQUIRED);
    }//onBackPressed   
    
    

    
	/*
	 * Set up form
	 */
	private void setUpForm(){
	   	//Campaign name
    	editCampaignName.setText((CharSequence) campaignData.get("name"));
    	
    	//Campaign budget
    	editCampaignBudget.setText(Converter.microamountToStr(campaignData.get("budget")));    	
    	cb_GoogleSearch.setChecked(Boolean.parseBoolean(campaignData.get("targetGoogleSearch")));

        cb_SearchPartners.setChecked(Boolean.parseBoolean(campaignData.get("targetSearchNetwork"))); 
    	cb_SearchPartners.setEnabled(Boolean.parseBoolean(campaignData.get("targetGoogleSearch")));

    	boolean targetContentNetworkValue = Boolean.parseBoolean(campaignData.get("targetContentNetwork"));
    	boolean targetContentContextualValue = Boolean.parseBoolean(campaignData.get("targetContentContextual"));

        if(targetContentNetworkValue){
        	cb_DisplayNetwork.setEnabled(true);
        	rb_Broadest.setEnabled(true);
        	rb_AllNetworks.setEnabled(true);
        	
            if (targetContentNetworkValue && targetContentContextualValue){
            	cb_DisplayNetwork.setChecked(true);
            	rb_Broadest.setChecked(true);
            } else if(targetContentNetworkValue && !targetContentContextualValue){
            	cb_DisplayNetwork.setChecked(true);
            	rb_AllNetworks.setChecked(true);
            }
        	
        } else {
        	cb_DisplayNetwork.setEnabled(false);
        	cb_DisplayNetwork.setChecked(false);
        	rb_Broadest.setEnabled(false);
        	rb_AllNetworks.setEnabled(false);
        }

        //Bidding strategy settings
        biddingStrategyTransition = campaignData.get("BiddingStrategyType");

        if(campaignData.get("BiddingStrategyType").equals("BudgetOptimizer")){
        	rb_BidingAutomatic.setChecked(true);
        	cb_BidingLimit.setEnabled(true);
        	rb_delivery_method_accelerated.setEnabled(false);
        	rb_delivery_method_standart.setEnabled(false);
        } else if(campaignData.get("BiddingStrategyType").equals("ManualCPC")){
        	rb_BidingManual.setChecked(true);
        	rb_delivery_method_accelerated.setEnabled(true);
        	rb_delivery_method_standart.setEnabled(true);
        }
        
        if(campaignData.get("bidLimit") != null)
	        if(!campaignData.get("bidLimit").equals("0")){
	            cb_BidingLimit.setChecked(true);
	        	editBidingLimit.setEnabled(true);
	        	editBidingLimit.setText(Converter.microamountToStr(campaignData.get("bidLimit")));   
	        }
       
        if(campaignData.get("deliveryMethod").equals("STANDARD")){
        	rb_delivery_method_standart.setChecked(true);
        } else {
        	rb_delivery_method_accelerated.setChecked(true);
        }
        
        if(campaignData.get("adServingOptimizationStatus").equals("OPTIMIZE")){
        	rb_adRotation_optimized.setChecked(true);
        } else {
        	rb_adRotation_rotate.setChecked(true);
        }
        
	}
	
    
	
    /*
     * Get Campaign data and put in form
     */
    Map<String, String> campaignData = new HashMap<String, String>();    
    private void getCampaignData(){
   	
    	CampaignResponseParser campaignParser = new CampaignResponseParser(
    				Communication.postSOAP(
    	    			CampaignService.URL_CAMPAIGN_SERVICE, 
    	    			CampaignService.getCampaignById(campaignId)
    	    		)  
    			);
    	
    	responseErrorString = campaignParser.checkForErrors();
    	campaignData.putAll(campaignParser.getCampaignData());
    }//getCampaignData

    
	
	/*
	 * Campaign Add Set operation
	 */
	private void campaignAddSetOperation(){
		String resp = Communication.postSOAP(
    			CampaignService.URL_CAMPAIGN_SERVICE, 
    			CampaignService.campaignOperation(campaignId, name, 
    					budget, manualCpc, bidLimit, netGoogle, 
    					netPartner, netDisplay, netBroadest, netAll, 
    					transitionFlag, deliveryMethod, adServingOptimizationStatus)
    		);

    	CampaignResponseParser campaignParser = new CampaignResponseParser(resp);
    	responseErrorString = campaignParser.checkForErrors();
	}//campaignAddSetOperation
	

	
    /*
     * Add campaign (button onClick handler)
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){	
    		runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
    }//onClick_addCampaign
     
   
    
    /*
     * Collecting and validating form data
     */
    private String name;
    private String budget;
    
    private boolean manualCpc;
    private boolean enableBidLimit;
    private String bidLimit = null;
    
    private boolean netGoogle = false;
    private boolean netPartner = false; 
    private boolean netDisplay = false; 
    private boolean netBroadest = false; 
    private boolean netAll = false;
    private boolean transitionFlag = false;

    private boolean deliveryMethod = true;
    private boolean adServingOptimizationStatus = true;
    
    private boolean isDataValid(){
    	boolean result = true;
    	
    	//Get name
    	name = editCampaignName.getText().toString();
    	//Get budget
    	budget = editCampaignBudget.getText().toString();
    	//Get net settings
    	netGoogle = cb_GoogleSearch.isChecked();    	
   
    	if(netGoogle){
        	netPartner = cb_SearchPartners.isChecked(); 
    	} else {
    		netPartner = false;
    	}
    	
    	netDisplay = cb_DisplayNetwork.isChecked();   
    	
    	if(netDisplay){
        	netBroadest = rb_Broadest.isChecked();
        	netAll = rb_AllNetworks.isChecked();    		
    	} else {
    		netBroadest = false;
    		netAll = false;
    	}
    	   	
    	//Get bidding flag
    	manualCpc = rb_BidingManual.isChecked();
    	
    	//Set transition Flag
    	if(biddingStrategyTransition != null)
	    	if(manualCpc && biddingStrategyTransition.equals("BudgetOptimizer")){
	    		transitionFlag = true;
	    	} else if(!manualCpc && biddingStrategyTransition.equals("ManualCPC")){
	    		transitionFlag = true;
	    	}
    	
    	//Get bid limit
    	enableBidLimit = cb_BidingLimit.isChecked();    	

    	//Validate data
    	if(!DataValidator.isName(name)) {
    		formErrorString = getString(R.string.msg_invalid_campaign_name);
    		editCampaignName.requestFocus();
    		result = false;
    	} else if(!DataValidator.isAmount(budget, false)) {
    		formErrorString = getString(R.string.msg_invalid_campaign_budget);
    		editCampaignBudget.requestFocus();
    		result = false;
    	} else if(!manualCpc && enableBidLimit){
        	bidLimit = editBidingLimit.getText().toString();  	
        	if(!DataValidator.isAmount(bidLimit, true)) {
        		formErrorString = getString(R.string.msg_invalid_campaign_bidLimit);
        		editBidingLimit.requestFocus();
        		result = false;
        	}      	
    	}
    	
    	deliveryMethod = rb_delivery_method_standart.isChecked() ? true : false;
    	adServingOptimizationStatus = rb_adRotation_optimized.isChecked() ? true : false;
    	
    	return result;
    }//isDataValid
    
   
    
    /*
     * Form Logic
     */
    public CampaignFormAddSetLogic logic = new CampaignFormAddSetLogic(this);
    public void setLogic(View v){
    	logic.setLogic(v);
    }//setLogic
    
}
